package com.bwie.kanjia.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.bwie.common.utils.R;
import com.bwie.kanjia.dao.ActDao;
import com.bwie.kanjia.dao.OrderDao;
import com.bwie.kanjia.entity.ActEntity;
import com.bwie.kanjia.entity.OrderEntity;
import com.bwie.kanjia.feignservice.UserFeign;
import com.bwie.kanjia.service.ActService;
import com.bwie.kanjia.vo.GoodsVo;
import com.bwie.kanjia.vo.UserVo;
import org.aspectj.lang.annotation.Around;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.common.utils.PageUtils;
import com.bwie.common.utils.Query;

import com.bwie.kanjia.dao.KeepDao;
import com.bwie.kanjia.entity.KeepEntity;
import com.bwie.kanjia.service.KeepService;
import org.springframework.transaction.annotation.Transactional;


@Service("keepService")
public class KeepServiceImpl extends ServiceImpl<KeepDao, KeepEntity> implements KeepService {

    @Autowired
    private ActDao actDao;
    @Autowired
    private OrderDao orderDao;


    public static final int MACHINE_ID = 2;


    @Autowired
    private UserFeign userFeign;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<KeepEntity> page = this.page(
                new Query<KeepEntity>().getPage(params),
                new QueryWrapper<KeepEntity>()
        );

        return new PageUtils(page);
    }

    //随机生成订单号
    public static String getOrderNumber() {
        int machineId = MACHINE_ID;//随机给个前缀

        //UUID.randomUUID().toString()是javaJDK提供的一个自动生成主键的方法
        int hashCodeV = UUID.randomUUID().toString().hashCode();
        System.out.println("hashCodeV：" + hashCodeV);
        if (hashCodeV < 0) {//有可能是负数,所以判断一下
            hashCodeV = -hashCodeV;
        }

        Date date=new Date();
        //15为长度
        //%0相当于一个占位符，而d就是填充的数据。
        //0是在arr转化为字符后，长度达不到length的时候，前面以0 补足。
        //d是个占位符，会被arr所替换。
        return machineId + String.format("%015d", hashCodeV)+date.getTime();

        //测试数据
        //hashCodeV：238482216
        //10000002384822161645710818379
    }

    //订单
    @Override
    @Transactional
    public R saves(KeepEntity keep) {
        //根据传入的actId和userId获取信息
        ActEntity actEntity = actDao.selectById(keep.getActId());
        keep.setGoodsId(actEntity.getGoodsId());
        R r = userFeign.goodsinfo(actEntity.getGoodsId());
        GoodsVo goodsVo = r.getData(new TypeReference<GoodsVo>() {
        });

        //feign调用user获取信息
        R info = userFeign.info(keep.getUserId());
        UserVo userVo = info.getData(new TypeReference<UserVo>() {
        });
        Integer count=baseMapper.selectByUidAndAid(keep.getUserId(),keep.getActId());
        if (count>0){
            return R.error("您已经参与过该活动");
        }
        keep.setUserName(userVo.getNickname());
        keep.setGoodsName(goodsVo.getGoodsName());
        keep.setGoodsSize(actEntity.getGoodsSize());
        keep.setKeepStart(new Date());
        keep.setKeepStatus(0);//状态0 正在砍价 1 砍价成功 2 砍价失败 3 未付款 4订单完成

        keep.setDdh(getOrderNumber());//生成订单号
        //活动价格和最终价格先默认都为活动价格
        keep.setActMoney(actEntity.getActPrice());
        keep.setKeepMoney(actEntity.getGoodsPrice());
          baseMapper.insert(keep);

        return R.ok().put("keepId",keep.getKeepId());
    }

    @Override
    public R kanjia(Long userId, String id, Integer actId) {
        //根据砍价人id和用户id和活动id判断是不是重复帮砍价
        Integer count=orderDao.selectByIds(id,userId,actId);
        if (count==0){
            //根据actId查询活动信息
            ActEntity actEntity = actDao.selectById(actId);
            //根据userId和actId获取订单信息
            KeepEntity keepEntity=baseMapper.getKeepByUA(Long.parseLong(id),actId);
            //判断 活动标记
            if (actEntity.getActFlag()==1){ //1：砍几刀至最低价  2:每刀砍10元直至最低价
                //判断最终价格已经砍到活动价格就不砍了
                if (keepEntity.getKeepMoney()!=keepEntity.getActMoney()){
                    //1.规则
                    Integer actRule = actEntity.getActRule();//一共砍几刀
                    //2.获取订单表中的 活动价格 和最终价格（没砍）
                    // 计算差价 计算每一刀砍多少钱
                    Double num=keepEntity.getKeepMoney()-keepEntity.getActMoney();
                    Double NumAvg=num/actRule;//每一刀砍多少

                    //去修改 ---砍完的最终价格
                    keepEntity.setKeepMoney(keepEntity.getKeepMoney()-NumAvg);
                    baseMapper.updateById(keepEntity);
                    if (keepEntity.getKeepMoney()==keepEntity.getActMoney()){
                        //这个时候如果最终价格已经砍到活动价格 就去修改状态
                        keepEntity.setKeepStatus(1);//状态0 正在砍价 1 砍价成功 2 砍价失败 3 未付款 4订单完成
                        baseMapper.updateById(keepEntity);
                    }
                    //去添加砍价记录表
                    OrderEntity orderEntity = new OrderEntity();
                    orderEntity.setUserId(Long.parseLong(id));//获取到用户id
                    orderEntity.setActId(actId);
                    orderEntity.setOrderTime(new Date());
                    orderEntity.setOrderNum(1);
                    orderEntity.setOrderPrice(NumAvg);//帮砍掉的价钱
                    orderEntity.setHelpeople(userId+"");//帮砍人-----登录的userid
                    orderDao.insert(orderEntity);
                    return R.ok("砍价成功");
                }
                return R.error("已经最低价格啦");
            }
            //1：砍几刀至最低价  2:每刀组多砍10元直至最低价
            if (actEntity.getActFlag()==2){
                //判断最终价格已经砍到活动价格就不砍了
                if (keepEntity.getKeepMoney()!=keepEntity.getActMoney()){
                    //随机生成一个商家设计的数字 以内double类型的数字，作为帮砍的价钱
                    double d =  actEntity.getActRule()- Math.random() * (actEntity.getActRule() - 1);
                    DecimalFormat df = new DecimalFormat("0.00");
                    Double  orderPrice= Double.valueOf(df.format(d));

                    //如果随机值和最终价钱差值 小于活动价格
                    if ((keepEntity.getKeepMoney()-orderPrice)<keepEntity.getActMoney()){
                        //就默认砍到最低价
                        //给keep——money赋值为act——money 也就是最终价钱
                        keepEntity.setKeepMoney(keepEntity.getActMoney());
                        baseMapper.updateById(keepEntity);
                        //这个时候最终价格已经砍到活动价格 就去修改状态
                        keepEntity.setKeepStatus(1);//状态0 正在砍价 1 砍价成功 2 砍价失败 3 未付款 4订单完成
                        baseMapper.updateById(keepEntity);
                    }else {
                        //修改订单中的money
                        keepEntity.setKeepMoney(keepEntity.getKeepMoney()-orderPrice);
                        baseMapper.updateById(keepEntity);
                        if (keepEntity.getKeepMoney()==keepEntity.getActMoney()){
                            //这个时候如果最终价格已经砍到活动价格 就去修改状态
                            keepEntity.setKeepStatus(1);//状态0 正在砍价 1 砍价成功 2 砍价失败 3 未付款 4订单完成
                            baseMapper.updateById(keepEntity);
                        }
                    }
                    //去添加砍价记录表
                    OrderEntity orderEntity = new OrderEntity();
                    orderEntity.setUserId(Long.parseLong(id));//获取到用户id
                    orderEntity.setActId(actId);
                    orderEntity.setOrderTime(new Date());
                    orderEntity.setOrderNum(1);
                    orderEntity.setOrderPrice(orderPrice);//帮砍掉的价钱
                    orderEntity.setHelpeople(userId+"");//帮砍人-----登录的userid
                    orderDao.insert(orderEntity);
                    return R.ok("砍价成功");

                }
                return R.error("已经最低价格啦");
            }
        }


        return R.error("已经帮忙砍过价啦");
    }

}